<template>
  <!-- 树形下拉选择器：支持仅选择末级、过滤禁用分类 -->
  <el-tree-select
    v-model="innerValue"
    :data="displayData"
    :props="{ value: 'id', label: 'name', children: 'children', disabled: 'disabled' }"
    :render-after-expand="false"
    :filterable="true"
    :clearable="true"
    :placeholder="placeholder"
    :check-strictly="!onlyLeaf"
    @change="emitChange"
  />
</template>

<script setup>
// 分类树选择器组件：用于父分类选择或商品所属分类选择
// 支持 onlyLeaf 限制仅选择末级分类，仅显示启用状态分类
import { computed } from 'vue'
import { treeComputed } from '../store/categories'

const props = defineProps({
  modelValue: { type: [Number, null], default: null },
  data: { type: Array, default: () => [] },
  onlyLeaf: { type: Boolean, default: false },
  showOnlyEnabled: { type: Boolean, default: false },
  disabledIds: { type: Array, default: () => [] },
  placeholder: { type: String, default: '请选择分类' }
})
const emit = defineEmits(['update:modelValue', 'change'])

const sourceTree = computed(() => (props.data?.length ? props.data : treeComputed.value))

// 根据配置过滤禁用与禁选项
const displayData = computed(() => {
  const walk = (nodes) => nodes.map(n => {
    const enabledOk = props.showOnlyEnabled ? n.status === 'enabled' : true
    const node = { ...n }
    node.disabled = props.disabledIds.includes(n.id)
    node.children = n.children?.length ? walk(n.children) : []
    return enabledOk ? node : null
  }).filter(Boolean)
  return walk(sourceTree.value)
})

const innerValue = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v)
})

function emitChange(v){
  emit('change', v)
}
</script>

<style scoped>
</style>